package com.lu.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.lu.common.utils.MD5Utils;
import com.lu.common.utils.R;
import com.lu.common.utils.TokenUtils;
import com.lu.system.user.domain.MenuDO;
import com.lu.system.user.domain.Tree;
import com.lu.system.user.domain.UserDO;
import com.lu.system.user.service.MenuService;
import com.lu.system.user.service.UserService;
import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/systemLogin")
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;

    @PostMapping(value = "/toLoginMsg")
    public R toLoginMsg(){
        return R.error("token失效请求重新登陆");
    }

    /**
     *
     * @param username
     * @param password
     * @return 返回tokenJwt
     * @throws Exception
     */
    @PostMapping("/login")
    public R login(String username,String password) throws Exception{
        Map<String,Object> map = new HashMap<>();
        map.put("username",username);
        UserDO userDO = null;
        List<UserDO> userDOList = userService.list(map);
        int i = 7/0;
        if(userDOList.size()>1){
            return R.error("系统账号异常！");
        }else if(userDOList.size()==0){
            return R.error("账号不存在！");
        }
        //获取用户信息
        userDO = userDOList.get(0);
        //MD5密码验证
        if(!MD5Utils.encrypt(username,password).equals(userDO.getPassword())){
            return R.error("密码错误！");
        }
        //验证成功，创建令牌
        String tokenJwt = TokenUtils.createJWT(JSONObject.toJSONString(userDO));
        return R.ok(tokenJwt);
    }

    @GetMapping("/menu")
    public R indexMenu(HttpServletRequest request) throws Exception{
        UserDO userDO = TokenUtils.parseJwtForUserInfo(request);
        List<Tree<MenuDO>> menus = menuService.listMenuTree(userDO.getUserId());
        Map<String, Object> map = new HashMap();
        map.put("data",menus);
        return R.ok(map);
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping(value = "/getUserInfo")
    public R getUserInfo(HttpServletRequest request) throws Exception {
        R r=new R();
        UserDO userDO =TokenUtils.parseJwtForUserInfo(request);
        r.put("code",0);
        r.put("msg","获取用户信息成功");
        r.put("data",userDO);
        return  r;
    }

}
